package cn.iocoder.springboot.labs;

import cn.iocoder.springboot.labs.service.FileService;
import cn.iocoder.springboot.labs.config.FileTypeDebugger;
import cn.iocoder.springboot.labs.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Api(tags = "mino API 接口")
public class FileController {
    private final FileService fileService;
    @Autowired
    private FileTypeDebugger fileTypeDebugger;

    @PostMapping("/image")
    public Result<String> imageUpload(@RequestParam("file") MultipartFile file) throws IOException {

        // 运行文件类型分析
        fileTypeDebugger.analyzeFileType(file);

        // 获取实际的文件类型
        String actualType = enhancedFileTypeDetection(file);
        String url = fileService.imageUpload(file);
        return Result.success(url);
    }

    /**
     * 增强的文件类型检测方法
     */
    public static String enhancedFileTypeDetection(MultipartFile file) {
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();

        // 1. 如果 MIME 类型为 null，根据文件名猜测
        if (contentType == null) {
            return guessTypeFromFilename(filename);
        }

        // 2. 扩展的 MIME 类型分类
        Map<String, String> mimeCategories = new HashMap<>();

        // 图片类型
        mimeCategories.put("image/jpeg", "image");
        mimeCategories.put("image/png", "image");
        mimeCategories.put("image/gif", "image");
        mimeCategories.put("image/bmp", "image");
        mimeCategories.put("image/webp", "image");
        mimeCategories.put("image/svg+xml", "image");

        // 文档类型
        mimeCategories.put("application/pdf", "document");
        mimeCategories.put("application/msword", "document");
        mimeCategories.put("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document");
        mimeCategories.put("application/vnd.ms-excel", "document");
        mimeCategories.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "document");
        mimeCategories.put("application/vnd.ms-powerpoint", "document");
        mimeCategories.put("application/vnd.openxmlformats-officedocument.presentationml.presentation", "document");

        // 文本类型
        mimeCategories.put("text/plain", "text");
        mimeCategories.put("text/html", "text");
        mimeCategories.put("text/css", "text");
        mimeCategories.put("text/csv", "text");
        mimeCategories.put("application/json", "text");
        mimeCategories.put("application/xml", "text");

        // 压缩文件
        mimeCategories.put("application/zip", "archive");
        mimeCategories.put("application/x-zip-compressed", "archive");
        mimeCategories.put("application/x-rar-compressed", "archive");
        mimeCategories.put("application/gzip", "archive");

        // 音频视频
        mimeCategories.put("audio/mpeg", "audio");
        mimeCategories.put("audio/wav", "audio");
        mimeCategories.put("video/mp4", "video");
        mimeCategories.put("video/avi", "video");

        // 检查已知的 MIME 类型
        if (mimeCategories.containsKey(contentType)) {
            return mimeCategories.get(contentType);
        }

        // 3. 基于主类型的通用分类
        if (contentType.startsWith("image/")) return "image";
        if (contentType.startsWith("text/")) return "text";
        if (contentType.startsWith("video/")) return "video";
        if (contentType.startsWith("audio/")) return "audio";
        if (contentType.startsWith("application/")) return "document";

        return "other";
    }

    /**
     * 根据文件名猜测文件类型
     */
    private static String guessTypeFromFilename(String filename) {
        if (filename == null) return "unknown";

        String extension = filename.toLowerCase();
        if (extension.contains(".")) {
            extension = extension.substring(extension.lastIndexOf("."));
        }

        switch (extension) {
            case ".jpg":
            case ".jpeg":
            case ".png":
            case ".gif":
            case ".bmp":
            case ".webp":
                return "image";
            case ".pdf":
            case ".doc":
            case ".docx":
            case ".xls":
            case ".xlsx":
            case ".ppt":
            case ".pptx":
                return "document";
            case ".txt":
            case ".log":
            case ".csv":
            case ".json":
            case ".xml":
                return "text";
            case ".zip":
            case ".rar":
            case ".7z":
            case ".tar":
            case ".gz":
                return "archive";
            case ".mp3":
            case ".wav":
            case ".flac":
                return "audio";
            case ".mp4":
            case ".avi":
            case ".mov":
            case ".wmv":
                return "video";
            default:
                return "other";
        }
    }

    @GetMapping("/image")
    public void imageDownLoad(HttpServletResponse response, String url) throws IOException {
        fileService.imageDownload(response, url);
    }

    @ApiOperation("图片删除")
    @DeleteMapping("/image")

    public Result<Void> imageDelete(String url) {
        fileService.imageDelete(url);
        return Result.success();
    }
}
